package org.linlinjava.litemall.admin.web;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeOrderSettleModel;
import com.alipay.api.domain.OpenApiRoyaltyDetailInfoPojo;
import com.alipay.api.request.AlipayTradeOrderSettleRequest;
import com.alipay.api.response.AlipayTradeOrderSettleResponse;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.admin.annotation.LoginAdmin;
import org.linlinjava.litemall.admin.strategy.AliPayModelListService;
import org.linlinjava.litemall.core.alipay.config.AliPayProperties;
import org.linlinjava.litemall.core.notify.NotifyService;
import org.linlinjava.litemall.core.notify.NotifyType;
import org.linlinjava.litemall.core.systemConfig.SystemConfig;
import org.linlinjava.litemall.core.util.LitemallMechanismToVo;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.core.util.bcrypt.BCryptPasswordEncoder;
import org.linlinjava.litemall.db.domain.LitemallConfig;
import org.linlinjava.litemall.db.domain.LitemallMechanism;
import org.linlinjava.litemall.db.domain.LitemallMechanismUser;
import org.linlinjava.litemall.db.domain.LitemallWalletRecord;
import org.linlinjava.litemall.db.service.LitemallConfigService;
import org.linlinjava.litemall.db.service.LitemallMechanismService;
import org.linlinjava.litemall.db.service.LitemallMechanismUserService;
import org.linlinjava.litemall.db.service.LitemallWalletRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/mechanism")
public class LitemallMechanismController {
	private final Log logger = LogFactory.getLog(LitemallMechanismController.class);

	@Autowired
	private LitemallMechanismService mechanismService;

	@Autowired
	private LitemallMechanismUserService mechanismUserService;

	@Autowired
	private LitemallConfigService litemallConfigService;

	@Autowired
	private LitemallMechanismService litemallMechanismService;

	@Autowired
	private PlatformTransactionManager txManager;

	@Autowired
	private NotifyService notifyService;

	@Autowired
	private AliPayModelListService aliPayModelListService;

	@Autowired
	private LitemallWalletRecordService litemallWalletRecordService;

	/**
	 * 1,2等级
	 */
	private static ArrayList<String> ARRAY_LEVEL1_LEVEL2 = new ArrayList<String>() {{
		add("1");
		add("2");
	}};

	private static int THREE = 3;

	private static String LEVEL_THREE = "3";

	private static String LEVEL_FOUR = "4";

	private AlipayClient alipayClient;

	@Autowired
	private LitemallMechanismToVo litemallMechanismToVo;

	@Autowired
	private AliPayProperties aliPayProperties;

	private AlipayClient getAlipayClient() {
		if (alipayClient == null) {
			createClient();
		}
		return alipayClient;
	}

	private synchronized void createClient() {
		if (alipayClient == null) {
			alipayClient = new DefaultAlipayClient(aliPayProperties.getOpenApiDomain(),
				aliPayProperties.getAppid(),
				aliPayProperties.getPrivateKey(),
				"json",
				"GBK",
				aliPayProperties.getAlipayPublicKey(),
				"RSA2");
		}
	}

	@GetMapping("/list")
	public Object list(
		@LoginAdmin Integer adminId,
		String name,
		String content,
		String legalPerson,
		String telephone,
		@RequestParam(value = "page", defaultValue = "1") Integer page,
		@RequestParam(value = "limit", defaultValue = "10") Integer limit,
		String sort,
		String mcategoryId,
		String level,
		String order) {
		if (adminId == null) {
			return ResponseUtil.unlogin();
		}
		List<Byte> listB = new ArrayList<Byte>();
		listB.add((byte)0);
		listB.add((byte)2);
		listB.add((byte)4);
		List<LitemallMechanism> adList = mechanismService.querySelective(name, content, legalPerson, telephone, page, limit, sort, mcategoryId, level, listB, order);
		long total = PageInfo.of(adList).getTotal();
		Map<String, Object> data = new HashMap<>();
		data.put("total", total);
		data.put("items", adList);
		return ResponseUtil.ok(data);
	}

	@GetMapping("/totalList")
	public Object totalList(
		@LoginAdmin Integer adminId, String name, String content, String legalPerson, String telephone, String sort, String order) {

		List<LitemallMechanism> adList = mechanismService.queryTotalSelective(name, content, legalPerson, telephone, sort, order);

		Map<String, Object> data = new HashMap<>();
		data.put("items", adList);

		return ResponseUtil.ok(data);
	}

	@GetMapping("/affiliation")
	public Object affiliation(@LoginAdmin Integer adminId, String level, String id, String name) {
		if (adminId == null) {
			return ResponseUtil.unlogin();
		}
		if (level == null) {
			level = "0";
		}
		Map<String, Object> data = new HashMap<>();
		List<LitemallMechanism> lmList = new ArrayList<>();
		List<Map<String, Object>> brandList = new ArrayList<>(lmList.size());
		if (level == null) {
			data.put("brandList", brandList);
		} else {
			lmList = mechanismService.queryLikeName(level, id, name);
			for (LitemallMechanism brand : lmList) {
				Map<String, Object> b = new HashMap<>(2);
				b.put("value", brand.getName());
				b.put("id", brand.getId());
				brandList.add(b);
			}
			data.put("brandList", brandList);
		}
		return ResponseUtil.ok(data);
	}

	@GetMapping("/getaffiliation")
	public Object getaffiliation(@LoginAdmin Integer adminId, Integer affiliation) {
		if (adminId == null) {
			return ResponseUtil.unlogin();
		}
		LitemallMechanism mechanism = mechanismService.findById(affiliation);
		Map<String, Object> data = new HashMap<>();
		if (mechanism != null) {
			data.put("affText", mechanism.getName());
		} else {
			data.put("affText", "");
		}
		return ResponseUtil.ok(data);
	}

	@PostMapping("/showMechanim")
	public Object showMechanim(@LoginAdmin Integer adminId, @RequestBody LitemallMechanism mechansim) {
		if (adminId == null) {
			return ResponseUtil.unlogin();
		}
		int id = mechansim.getId();

		LitemallMechanism list = mechanismService.findById(id);
		Map<String, Object> addressVo = litemallMechanismToVo.toVo(list);
		Map<String, Object> data = new HashMap<>();
		data.put("listMechanism", addressVo);
		return ResponseUtil.ok(data);
	}

	/**
	 * 审核成功
	 *
	 * @param adminId
	 * @param id      机构id
	 * @param words   备注
	 * @return 成功或失败
	 */
	@GetMapping("/checkSuccess")
	public Object checkSuccess(@LoginAdmin Integer adminId, Integer id, String words) {
		if (adminId == null) {
			return ResponseUtil.unlogin();
		}
		if (id == null) {
			return ResponseUtil.fail();
		}

		// 机构信息
		LitemallMechanism mechanism = litemallMechanismService.findById(id);
		String level = mechanism.getLevel().toString();
		//判断是新用户还是续费用户，如果是新用户，发送账号及密码。如果不是，则提示
		//如果是老用户升级，那么他机构账户上会有到期时间，而新用户是没有的
		//true为新用户 false为老用户
		boolean message = mechanism.getEndTime() == null ? true : false;

		// 代理信息
		LitemallMechanism litemallMechanism = litemallMechanismService.findById(mechanism.getAffiliation());

		if (ARRAY_LEVEL1_LEVEL2.contains(level)) {
			mechanism.setEndTime(LocalDateTime.now().plusYears(1));
			if (litemallMechanism != null) {
				litemallMechanism.setLeveTwoNum(litemallMechanism.getLeveTwoNum() + 1);
				mechanismService.updateById(litemallMechanism);
			}
		} else if (LEVEL_THREE.equals(level)) {
			mechanism.setEndTime(LocalDateTime.now().plusYears(3));
			if (litemallMechanism != null) {
				litemallMechanism.setLevelThreeNum(litemallMechanism.getLevelThreeNum() + 1);
				mechanismService.updateById(litemallMechanism);
			}
		} else if (LEVEL_FOUR.equals(level)) {
			mechanism.setEndTime(LocalDateTime.now().plusYears(199));
			if (litemallMechanism != null) {
				litemallMechanism.setLevelFourNum(litemallMechanism.getLevelFourNum() + 1);
				mechanismService.updateById(litemallMechanism);
			}
		}

		mechanism.setStartTime(LocalDateTime.now());
		mechanism.setDeleted(false);
		mechanism.setCheckStatus((byte)2);
		mechanismService.updateById(mechanism);

		LitemallConfig litemallConfig = litemallConfigService.findById(10000004);
		//发送短信信息通知用户账户注册成功，账户与密码一并发送
		if (message) {
			LitemallMechanismUser litemallMechanismUser = new LitemallMechanismUser();
			litemallMechanismUser.setFullName(mechanism.getLegalPerson());
			litemallMechanismUser.setMechanismId(id);
			BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
			String encodedPassword = encoder.encode(litemallConfig.getValue() + "");
			litemallMechanismUser.setPassword(encodedPassword);
			litemallMechanismUser.setAddTime(LocalDateTime.now());

			int i = 1;
			String name;
			name = mechanism.getLegalPerson() + id;
			while (mechanismService.countSelective(null, null, name) != 0) {
				i++;
				int newNum = i + id;
				name = mechanism.getLegalPerson() + newNum;
			}
			litemallMechanismUser.setUsername(name);
			mechanismUserService.add(litemallMechanismUser);

			// 异步发送短信
			new Thread(() -> {
				String params = new String(
					"{\"username\":\"" + litemallMechanismUser.getUsername() + "\",\"password\":\"" + litemallConfig.getValue() + "\",\"servicetel\":\"" + SystemConfig.getServiceNum() + "\"}");
				notifyService.notifySmsTemplate(mechanism.getTelephone(), NotifyType.JUDGESUCCESS, params);
			}).start();
		} else {
			// 提示用户审核结果(成功)
			LitemallMechanismUser litemallMechanismUser = mechanismUserService.queryByMechanismId(mechanism.getId());
			System.out.println(mechanism.getTelephone());
			new Thread(() -> {
				String params = new String(
					"{\"username\":\"" + litemallMechanismUser.getUsername() + "\",\"password\":\"" + litemallConfig.getValue() + "\",\"servicetel\":\"" + SystemConfig.getServiceNum() + "\"}");
				notifyService.notifySmsTemplate(mechanism.getTelephone(), NotifyType.JUDGESUCCESS, params);
			}).start();
		}
		return ResponseUtil.ok();
	}

	/**
	 * 分账功能
	 *
	 * @param adminId
	 * @param id
	 * @return
	 */
	@GetMapping("/subAccount")
	public Object subAccount(@LoginAdmin Integer adminId, Integer id) {
		if (adminId == null) {
			return ResponseUtil.unlogin();
		}
		if (id == null) {
			return ResponseUtil.fail();
		}
		// 分账成功与否标志
		boolean flag;
		// 机构信息
		LitemallMechanism mechanism = litemallMechanismService.findById(id);
		String level = mechanism.getLevel().toString();
		String transOut = "已分账";
		// 机构交钱信息(钱包)
		LitemallWalletRecord litemallWalletRecord = litemallWalletRecordService.queryByRecordSn(mechanism.getRecordSn());
		if (mechanism.getAffiliation() != null) {
			// 代理信息
			LitemallMechanism litemallMechanism = litemallMechanismService.findById(mechanism.getAffiliation());
			if (litemallMechanism.getAlpay() == null) {
				return ResponseUtil.fail(403, "代理方还未维护支付宝到账的pid,请联系对方再试");
			}
			if (litemallMechanism.getLevel() != null) {
				String proxyLevel = litemallMechanism.getLevel().toString();
				if (!StringUtil.isEmpty(litemallMechanism.getAlpay()) && Integer.parseInt(proxyLevel) >= THREE) {
					if (litemallMechanism.getProxyUseFlag() != null && litemallMechanism.getProxyUseFlag()) {
						OpenApiRoyaltyDetailInfoPojo openApiRoyaltyDetailInfoPojo = aliPayModelListService.saleMethod(proxyLevel + level, litemallMechanism);
						transOut += openApiRoyaltyDetailInfoPojo.getAmount();
						if (openApiRoyaltyDetailInfoPojo != null) {
							flag = this.fenZhang(litemallWalletRecord.getPayId(), openApiRoyaltyDetailInfoPojo);
							if (!flag) {
								return ResponseUtil.fail(403, "后台分账失败,钱包订单号：" + litemallWalletRecord.getPayId());
							} else {
								mechanism.setCheckStatus((byte)4);
								mechanismService.updateById(mechanism);
							}
						}
					} else {
						return ResponseUtil.ok("代理账户已被禁用，无需分账");
					}
				} else {
					return ResponseUtil.ok("代理等级为标准一年，无需分账");
				}
			}
		}
		return ResponseUtil.ok(transOut);
	}

	/**
	 * 分账功能
	 *
	 * @return true 成功  false 失败
	 */
	public boolean fenZhang(String payId, OpenApiRoyaltyDetailInfoPojo openApiRoyaltyDetailInfoPojo) {
		logger.info("分账订单号：" + payId + "，支出：" + openApiRoyaltyDetailInfoPojo.getTransOut() + ",收入：" + openApiRoyaltyDetailInfoPojo.getTransIn() + ",金额：" + openApiRoyaltyDetailInfoPojo.getAmount());
		boolean flag = true;
		AlipayTradeOrderSettleRequest request = new AlipayTradeOrderSettleRequest();
		AlipayTradeOrderSettleModel model = new AlipayTradeOrderSettleModel();
		//该笔分账的请求单号，每一次请求保证唯一
		model.setOutRequestNo(payId.substring(0, 10));
		//分账的交易的支付宝交易号
		model.setTradeNo(payId);
		// 声明OpenApiRoyaltyDetailInfoPojo方法用于传入royaltyParameters
		List<OpenApiRoyaltyDetailInfoPojo> royaltyParameters1 = new ArrayList<>();
		royaltyParameters1.add(openApiRoyaltyDetailInfoPojo);
		model.setRoyaltyParameters(royaltyParameters1);
		request.setBizModel(model);
		try {
			AlipayTradeOrderSettleResponse response = getAlipayClient().execute(request, "", aliPayProperties.getAppAuthToken());
			logger.info(response.getMsg());
			if (response.isSuccess()) {
				System.out.println("调用成功");
			} else {
				System.out.println("调用失败");
				flag = false;
			}
		}
		catch (AlipayApiException e) {
			e.printStackTrace();
		}
		return flag;
	}

	@GetMapping("/checkDefault")
	public Object checkDefault(@LoginAdmin Integer adminId, Integer id, String checkWord) {
		if (adminId == null) {
			return ResponseUtil.unlogin();
		}
		if (id == null) {
			return ResponseUtil.unlogin();
		}
		LitemallMechanism mechanism = new LitemallMechanism();
		mechanism.setCheckStatus((byte)3);
		mechanism.setId(id);
		mechanism.setCheckWord(checkWord);
		mechanismService.updateById(mechanism);

		LitemallMechanism mechanism1 = litemallMechanismService.findById(id);

		new Thread(() -> {
			String params = new String("{\"servicetel\":\"" + "15313035692" + "\"}");
			notifyService.notifySmsTemplate(mechanism1.getTelephone(), NotifyType.JUDGEFAILURE, params);
		}).start();
		return ResponseUtil.ok();
	}

	@PostMapping("/create")
	public Object create(@LoginAdmin Integer adminId, @RequestBody LitemallMechanism litemallMechanism) {
		if (adminId == null) {
			return ResponseUtil.unlogin();
		}
		litemallMechanism.setEndTime(litemallMechanism.getStartTime().plusYears(1));
		litemallMechanism.setUpdateTime(LocalDateTime.now());
		litemallMechanism.setIntegralAmountUsed((long)0);
		mechanismService.add(litemallMechanism);
		return ResponseUtil.ok(litemallMechanism);
	}

	@GetMapping("/name")
	public Object username(String status, Integer id, String name) {
		if (StringUtil.isEmpty(name)) {
			return ResponseUtil.badArgument();
		}
		int total = mechanismService.countSelective(status, id, name);
		if (total == 0) {
			return ResponseUtil.ok(true);
		}
		return ResponseUtil.ok(false);
	}

	@PostMapping("/import")
	public Object importAll(@LoginAdmin Integer adminId, @RequestBody Object data) {
		if (adminId == null) {
			return ResponseUtil.unlogin();
		}
		LitemallConfig litemallConfig = litemallConfigService.findById(10000004);

		LitemallMechanism litemallMechanism = new LitemallMechanism();
		LitemallMechanismUser litemallMechanismUser = new LitemallMechanismUser();

		LocalDateTime dateTime = LocalDateTime.now();

		DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

		Map<String, String> map = (Map<String, String>)data;

		String name = map.get("name");
		String legalPerson = map.get("legalPerson");
		String mobile = map.get("telephone");
		if (name == null || legalPerson == null || mobile == null) {
			String a = "主要信息不能为空";
			return ResponseUtil.ok(a);
		} else {
			int count = mechanismService.countMechanism(name, legalPerson);
			int legalPersonCount = mechanismService.countLegalPerson(legalPerson);
			int nameCount = mechanismService.countName(name);
			if (count == 0) {
				litemallMechanism.setAddress(map.get("address"));
				litemallMechanism.setLegalPerson(map.get("legalPerson"));
				litemallMechanism.setName(map.get("name"));
				litemallMechanism.setMechanismType(map.get("mechanismType"));
				litemallMechanism.setNickName(map.get("nickName"));
				litemallMechanism.setTelephone(map.get("telephone"));
				litemallMechanism.setStartTime(dateTime);
				litemallMechanism.setEndTime(dateTime.plusYears(1));
				litemallMechanism.setIntegralAmountAll(new Long(map.get("integralAmountAll")));
				//        litemallMechanismUser.setPassword(map.get("password"));
				litemallMechanismUser.setFullName(map.get("fullName"));
				litemallMechanismUser.setAddTime(dateTime);
				litemallMechanism.setUpdateTime(dateTime);
				BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
				String encodedPassword = encoder.encode(litemallConfig.getValue() + "");
				litemallMechanismUser.setPassword(encodedPassword);
				// 开启事务管理
				DefaultTransactionDefinition def = new DefaultTransactionDefinition();
				def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
				TransactionStatus status = txManager.getTransaction(def);
				try {
					//用于判断机构名称和机构管理员名称唯一
					if (mechanismService.countSelective(null, null, map.get("name")) == 0) {
						mechanismService.add(litemallMechanism);
						litemallMechanismUser.setMechanismId(litemallMechanism.getId());
						litemallMechanismUser.setUsername(map.get("username") + litemallMechanism.getId());
						if (mechanismUserService.countSeletive(null, null, litemallMechanismUser.getUsername()) == 0) {
							mechanismUserService.add(litemallMechanismUser);
							//成功导入机构管理员后发送短信通知
							new Thread(() -> {
								String params = new String("{\"username\":\"" + litemallMechanismUser.getUsername() + "\",\"password\":\"" + litemallConfig.getValue() + "\",\"startTime\":\"" + df
									.format(litemallMechanism.getStartTime()) + "\",\"endTime\":\"" + df.format(litemallMechanism.getEndTime()) + "\"}");
								notifyService.notifySmsTemplate(litemallMechanism.getTelephone(), NotifyType.GIVEMENOTIFY, params);
							}).start();
						}
					}

				}
				catch (Exception ex) {
					txManager.rollback(status);
					logger.error("系统内部错误", ex);
				}
				txManager.commit(status);
				((Map<String, Object>)data).put("count", count);
				return ResponseUtil.ok(data);
			} else {
				((Map<String, Object>)data).put("name", name);
				((Map<String, Object>)data).put("count", count);
				((Map<String, Object>)data).put("legalPersonCount", legalPersonCount);
				((Map<String, Object>)data).put("nameCount", nameCount);
				return ResponseUtil.ok(data);
			}
		}
	}

	@PostMapping("/reimport")
	public Object reimport(@LoginAdmin Integer adminId, @RequestBody Object data) {
		System.out.println("dddd");
		if (adminId == null) {
			return ResponseUtil.unlogin();
		}

		System.out.println(data);
		LitemallConfig litemallConfig = litemallConfigService.findById(10000004);

		LitemallMechanism litemallMechanism = new LitemallMechanism();
		LitemallMechanismUser litemallMechanismUser = new LitemallMechanismUser();

		LocalDateTime dateTime = LocalDateTime.now();

		DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		// 开启事务管理
		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
		TransactionStatus status = txManager.getTransaction(def);

		Map<String, String> map = (Map<String, String>)data;
		litemallMechanism.setAddress(map.get("address"));
		litemallMechanism.setLegalPerson(map.get("legalPerson"));
		litemallMechanism.setName(map.get("name"));
		litemallMechanism.setMechanismType(map.get("mechanismType"));
		litemallMechanism.setNickName(map.get("nickName"));
		litemallMechanism.setTelephone(map.get("telephone"));
		litemallMechanism.setStartTime(dateTime);
		litemallMechanism.setEndTime(dateTime.plusYears(1));
		litemallMechanism.setIntegralAmountAll(new Long(map.get("integralAmountAll")));
		//        litemallMechanismUser.setPassword(map.get("password"));
		litemallMechanismUser.setFullName(map.get("fullName"));
		litemallMechanismUser.setAddTime(dateTime);
		litemallMechanism.setUpdateTime(dateTime);
		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
		String encodedPassword = encoder.encode(litemallConfig.getValue() + "");
		litemallMechanismUser.setPassword(encodedPassword);
		try {
			//用于判断机构名称和机构管理员名称唯一
			if (mechanismService.countSelective(null, null, map.get("name")) == 0) {
				mechanismService.add(litemallMechanism);
				txManager.commit(status);
				System.out.println("aaaa" + litemallMechanism);
				litemallMechanismUser.setMechanismId(litemallMechanism.getId());
				litemallMechanismUser.setUsername(map.get("username") + litemallMechanism.getId());
				if (mechanismUserService.countSeletive(null, null, litemallMechanismUser.getUsername()) == 0) {
					mechanismUserService.add(litemallMechanismUser);
					//成功导入机构管理员后发送短信通知
					new Thread(() -> {
						String params = new String("{\"username\":\"" + litemallMechanismUser.getUsername() + "\",\"password\":\"" + litemallConfig.getValue() + "\",\"startTime\":\"" + df
							.format(litemallMechanism.getStartTime()) + "\",\"endTime\":\"" + df.format(litemallMechanism.getEndTime()) + "\"}");
						notifyService.notifySmsTemplate(litemallMechanism.getTelephone(), NotifyType.GIVEMENOTIFY, params);
					}).start();
				}

			}

		}
		catch (Exception ex) {
			txManager.rollback(status);
			logger.error("系统内部错误", ex);
		}

		return ResponseUtil.ok(data);
	}

	@GetMapping("/read")
	public Object read(@LoginAdmin Integer adminId, Integer id) {
		if (adminId == null) {
			return ResponseUtil.unlogin();
		}

		if (id == null) {
			return ResponseUtil.badArgument();
		}

		LitemallMechanism brand = mechanismService.findById(id);
		return ResponseUtil.ok(brand);
	}

	@PostMapping("/update")
	public Object update(@LoginAdmin Integer adminId, @RequestBody LitemallMechanism ad) {
		if (adminId == null) {
			return ResponseUtil.unlogin();
		}
		if(ad.getLevel()>2){
			LitemallMechanism litemallMechanism = mechanismService.findById(ad.getId());
			if(litemallMechanism.getLevel()<3){
				ad.setNewProxyFlag(true);
			}
			if(ad.getLevel()==3){
				ad.setEndTime(ad.getStartTime().plusYears(3));
			}else if(ad.getLevel()==4){
				ad.setEndTime(ad.getStartTime().plusYears(199));
			}
		}
		mechanismService.updateById(ad);
		return ResponseUtil.ok(ad);
	}

	@PostMapping("/delete")
	public Object delete(@LoginAdmin Integer adminId, @RequestBody LitemallMechanism ad) {
		if (adminId == null) {
			return ResponseUtil.unlogin();
		}
		mechanismUserService.deleteByMechanismId(ad.getId());
		mechanismService.deleteById(ad.getId());
		return ResponseUtil.ok();
	}
}
